﻿using ELearning.BLL;
using ELearning.Common;
using ELearning.Common.Azure;
using ELearning.Common.Extensions;
using ELearning.Common.Model;
using ELearning.Models;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Web;
using System.Web.Http;
using ELearning.API.Models;
using ELearning.Common.CommonStr;

namespace ELearning.API.Controllers.ElearningController
{
    public class EStudentStudySumController : BaseApiController
    {
        EAttachmentService eAttachmentService = new EAttachmentService();

        EStudentStudySumService eStudentStudySumService = new EStudentStudySumService();

        EStudentStudyRecordService eStudentStudyRecordService = new EStudentStudyRecordService();
        private ECourseSeriesService courseSeriesService = new ECourseSeriesService();
        private EProductService productService = new EProductService();
        /// <summary>
        /// 根据课件资源id更新学习记录总表
        /// </summary>
        /// <param name="EAttachmentID"></param>
        /// <returns></returns>
        [HttpGet, Route("api/StudentStudy/SaveStudy")]
        public ServiceResponse<bool> SaveStudy(Guid EAttachmentID)
        {
            var flag = false;
            EAttachment eAttachment = eAttachmentService.Find(w => w.ID == EAttachmentID);

            if (eAttachment == null)
            {
                return ServiceResponse<bool>.SuccessResponse(flag);
            }
            //根据课程Id 获取课程系列ID
            Guid csid = eStudentStudySumService.GetCSIDByCID(eAttachment.TeachingID);

            var estudentstudy = eStudentStudyRecordService.Find(w => w.TeaCoursePubID == eAttachment.TeachingID && w.StuID == CurrentUserModel.UserId);
            if (estudentstudy == null)
            {
                var es = new EStudentStudyRecord()
                {
                    ID = GuidUtil.NewSequentialId(),
                    TeaCoursePubID = eAttachment.TeachingID,
                    StuID = CurrentUserModel.UserId,
                    Creater = CurrentUserModel.LoginName,
                    CreateTime = DateTime.Now,
                    Modifyer = CurrentUserModel.LoginName,
                    ModifyTime = DateTime.Now,
                    IsAudit = true,
                    IsDelete = false,
                    IsPass = true,
                    IsStudy = true,
                    LearnCount = 0,
                    StudyMinute = 0,
                    StartTime = DateTime.Now,
                    EndTime = DateTime.Now,
                    OrgCode = ""
                };
                eStudentStudyRecordService.Add(es);

                if (csid != null)
                {
                    var studentsum = eStudentStudySumService.Find(w => w.StuID == CurrentUserModel.UserId && w.CSID == csid);
                    if (studentsum != null)
                    {
                        studentsum.countsum = courseSeriesService.GetCourseCountById(csid);
                        studentsum.CID = eAttachment.TeachingID;
                        studentsum.overcount = studentsum.overcount + 1;
                        studentsum.percentage = (studentsum.overcount * 100) / studentsum.countsum;
                        studentsum.Modifyer = CurrentUserModel.LoginName;
                        studentsum.ModifyTime = DateTime.Now;
                        flag = eStudentStudySumService.Update(studentsum);

                        if (studentsum.percentage == 100)
                        {
                            IntegralLogHelper.AddIntegralLog(IntegralConfigCode.FinishStudy100, CurrentUserModel.UserId, csid, csid, 0,CurrentUserModel.LoginName, "观看课程课件完成");

                        }
                        return ServiceResponse<bool>.SuccessResponse(flag);
                    }
                    else
                    {
                        return ServiceResponse<bool>.SuccessResponse(false);
                    }
                }
            }
            else
            {
                estudentstudy.EndTime = DateTime.Now;
                estudentstudy.LearnCount += 1;
                eStudentStudyRecordService.Update(estudentstudy);

                //更新总表

                if (csid != null)
                {
                    var studentsum = eStudentStudySumService.Find(w => w.StuID == CurrentUserModel.UserId && w.CSID == csid);
                    if (studentsum != null)
                    {
                        studentsum.countsum = courseSeriesService.GetCourseCountById(csid);
                        studentsum.CID = eAttachment.TeachingID;
                        studentsum.percentage = (studentsum.overcount * 100) / studentsum.countsum;
                        studentsum.Modifyer = CurrentUserModel.LoginName;
                        studentsum.ModifyTime = DateTime.Now;
                        flag = eStudentStudySumService.Update(studentsum);

                        if (studentsum.percentage == 100)
                        {
                            IntegralLogHelper.AddIntegralLog(IntegralConfigCode.FinishStudy100, CurrentUserModel.UserId, csid , csid, 0,CurrentUserModel.LoginName, "观看课程课件完成");

                        }
                        return ServiceResponse<bool>.SuccessResponse(flag);
                    }
                    else
                    {
                        return ServiceResponse<bool>.SuccessResponse(false);
                    }
                }
            }


            return ServiceResponse<bool>.SuccessResponse(flag);

        }

        [AllowAnonymous]
        [HttpGet, Route("api/StudentStudy/GetALLStudentProduct")]
        public ServiceResponse<string> GetALLStudentProduct()
        {
            List<StuStudyViewModel> myprod = new List<StuStudyViewModel>();

            Expression<Func<ECourseSeries, bool>> whereLamdba = u => !u.IsDelete;
            var courselist = courseSeriesService.FindList(whereLamdba).ToList();

            Expression<Func<EStudentStudySum, bool>> studyLamdba = u => !u.IsDelete;
            var StudySumList = eStudentStudySumService.FindList(studyLamdba).ToList();

            Expression<Func<EStudentStudyRecord, bool>> recordLamdba = u => !u.IsDelete;
            var recordList = eStudentStudyRecordService.FindList(recordLamdba).ToList();
            foreach (var sum in StudySumList)
            {
                //var prod = new StuStudyViewModel();
              

                var zilist = courseSeriesService.GetCourseSeriesById(sum.CSID).Select(w => w.ID).ToList();

                var zirecordlist = recordList.Where(w => w.StuID == sum.StuID && zilist.Contains(w.TeaCoursePubID)).ToList();
                foreach (var zi in zirecordlist)
                {
                    var pprod = new StuStudyViewModel();
                    pprod.ID = sum.ID;
                    pprod.StuID = sum.StuID;
                    pprod.CSID = sum.CSID;
                    pprod.overcount = sum.overcount;
                    pprod.countsum = sum.countsum;
                    pprod.percentage = sum.percentage;
                    pprod.Creater = sum.Creater;
                    pprod.PTitle = courselist.Find(w => w.ID == sum.CSID)?.Title;
                    //var v = zi.MapTo<sturecord, EStudentStudyRecord>();
                    //v.PTitle = productlist.Find(w => w.ID == zi.TeaCoursePubID)?.Title;
                    //prod.RecordItems.Add(v);
                  
                    pprod.ZJTitle= courselist.Find(w => w.ID == zi.TeaCoursePubID)?.Title;
                    pprod.StartTime = zi.StartTime;
                    pprod.EndTime = zi.EndTime;
                    pprod.LearnCount = zi.LearnCount;
                    myprod.Add(pprod);
                }
                //myprod.Add(prod);
            }
            var pp = myprod.OrderBy(w => w.Creater).ThenBy(w => w.PTitle).ThenBy(w=>w.ZJTitle).ToList();
            var extDt = pp.ToDataTable(null);
            var fileFullPath = GetPath();
            ExcelHelp.TableToExcelForXLSX(extDt, fileFullPath);
            var url = SaveFile("学习记录信息.xlsx", fileFullPath);
            return ServiceResponse<string>.SuccessResponse(url);
        }

        /// <summary>
        /// 获取文件保存路径
        /// </summary>
        private string GetPath()
        {
            var str = string.Empty;
            var virtualPath = "/UploadFile/Files/";
            var path = HttpContext.Current.Server.MapPath(virtualPath);
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
            var fileFullPath = $"{path}{DateTime.Now:yyyyMMddHHmmss}.xlsx";
            return fileFullPath;
        }
        /// <summary>
        /// 文件上传到blob
        /// </summary>
        private string SaveFile(string fileName, string fileFullPath)
        {
            //var fs = new FileStream(fileFullPath, FileMode.Open);
            var str = string.Empty;
            //var bc = new BlobController();
            //var blobName = BlobHelper.GetBlobName(fileName);
            //var blobResult = bc.CreateBlod(blobName);
            //if (blobResult == ApiResultEunm.Success || blobResult == ApiResultEunm.Exist)
            //{
            //    //创建文件
            //    var apiResult = bc.UploadFileByStream(fs, fileName);
            //    if (apiResult.apiResultEunm == ApiResultEunm.Success && !string.IsNullOrEmpty(apiResult.info))
            //    {
            //        str = apiResult.info;
            //    }
            //}
            //fs.Dispose();
            //File.Delete(fileFullPath);
            return str;
        }


    }
}